<template>
  <div ref="editorRef" class="editor" />
</template>

<script lang="ts" setup>
import { onMounted, onUnmounted, ref } from 'vue';
import * as monaco from 'monaco-editor';

// 定义组件属性
const props = defineProps({
  modelValue: { required: true, type: String },
});
// 定义组件事件
const emit = defineEmits(['update:modelValue']);
const DEFAULT_OPTIONS = {
  automaticLayout: true,
  minimap: {
    enabled: false,
  },
  scrollBeyondLastLine: false,
};
const editorRef = ref(null);
const editorInstance = ref<monaco.editor.IStandaloneCodeEditor>(null);
const initEditor = async(container: HTMLDivElement) => {
  try {
    editorInstance.value = monaco.editor.create(container, {
      ...DEFAULT_OPTIONS,
      value: props.modelValue,
      language: 'javascript',
    });
    monaco.editor.setTheme('vs-dark');

    // 监听编辑器内容变化，同步到父组件
    // editorInstance.value.onDidChangeModelContent(() => {
    //   const newValue = editorInstance.value.getValue();
    //   console.log('newValue', newValue);
    //   emit('update:modelValue', newValue); // 触发 v-model 更新
    // });
  } catch (error) {
    console.error(error);
  }
};
// 监听 props.modelValue 变化，同步到编辑器
// watch(() => props.modelValue, (newValue) => {
//       console.log('watch:modelValue', newValue);
//       if (editorInstance.value) {
//         // 避免编辑器自身修改触发的死循环
//         const currentValue = editorInstance.value.getValue();
//         if (newValue !== currentValue) {
//           editorInstance.value.setValue(newValue);
//         }
//       }
//     }
// );
/** 组件挂载时初始化编辑器 */
onMounted(() => {
  initEditor(editorRef.value);
});
/** 组件卸载时清理编辑器实例 */
onUnmounted(() => {
  if (editorInstance.value) {
    editorInstance.value.destroy();
  }
});
</script>

<style lang="scss" scoped>
.editor {
  width: 100%;
  min-height: 400px;
  overflow: hidden;
  border: 1px solid #e5e7eb;
  border-radius: 5px;
  box-sizing: border-box;
}
</style>
